package com.jzo2o.orders.manager.Handler;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jzo2o.api.trade.RefundRecordApi;
import com.jzo2o.api.trade.dto.response.ExecutionResultResDTO;
import com.jzo2o.api.trade.enums.RefundStatusEnum;
import com.jzo2o.common.constants.UserType;
import com.jzo2o.orders.base.enums.OrderRefundStatusEnum;
import com.jzo2o.orders.base.mapper.OrdersMapper;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.base.model.domain.OrdersRefund;
import com.jzo2o.orders.manager.model.dto.OrderCancelDTO;
import com.jzo2o.orders.manager.service.IOrdersCreateService;
import com.jzo2o.orders.manager.service.IOrdersManagerService;
import com.jzo2o.orders.manager.service.IOrdersRefundService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class OrdersHandler{
@Resource
    IOrdersCreateService iOrdersCreateService;
@Resource
    IOrdersManagerService iOrdersManagerService;

    /**
     * 定时任务 定时取消超时订单
     */
    @XxlJob(value = "cancelOverTimePayOrder")
    public  void cancelOverTimePayOrder()
    {
        //待取消订单

        List<Orders> orderslist = iOrdersCreateService.queryOverTimePayOrdersListByCount(10);
        if(CollUtil.isEmpty(orderslist))
        {
            XxlJobHelper.log("该订单列表为空");
            return;
        }
        for (Orders orders:orderslist)
        {
            //修改订单状态
            //增加取消表
            OrderCancelDTO orderCancelDTO= BeanUtil.toBean(orders,OrderCancelDTO.class);
            orderCancelDTO.setCurrentUserType(UserType.SYSTEM);
            orderCancelDTO.setCancelReason("订单超时支付，自动取消");
            iOrdersManagerService.cancel(orderCancelDTO);

        }


    }
    @Resource
    private IOrdersRefundService ordersRefundService;
    /**
     * 订单支付退款
     */
    public void handleRefundOrders() {
        //获取订单退款吧所有数据
        List<OrdersRefund> ordersRefundslist = ordersRefundService.queryRefundOrderListByCount(100);
        //循环退款
        for(OrdersRefund ordersRefund:ordersRefundslist)
        {
            requestRefundOrder(ordersRefund);
        }


    }

    /**
     * 请求退款
     * @param ordersRefund
     */
    @Resource
    private RefundRecordApi refundRecordApi;
    @Resource
    private OrdersHandler ordersHandler;
    @Resource
    private OrdersMapper ordersMapper;
    private void requestRefundOrder(OrdersRefund ordersRefund) {
        //请求退款
        ExecutionResultResDTO executionResultResDTO = null;
        try {
            executionResultResDTO = refundRecordApi.refundTrading(ordersRefund.getTradingOrderNo(), ordersRefund.getRealPayAmount());
        } catch (Exception e){
            e.printStackTrace();
        }
        if(executionResultResDTO!=null)
        {
            //退款后 更新订单状态
            ordersHandler.refundOrder(ordersRefund, executionResultResDTO);
        }

    }

    private void refundOrder(OrdersRefund ordersRefund, ExecutionResultResDTO executionResultResDTO) {
    //
        //根据响应结果更新退款状态
        int refundStatus = OrderRefundStatusEnum.REFUNDING.getStatus();//退款中
        if (ObjectUtil.equal(RefundStatusEnum.SUCCESS.getCode(), executionResultResDTO.getRefundStatus())) {
            //退款成功
            refundStatus = OrderRefundStatusEnum.REFUND_SUCCESS.getStatus();
        } else if (ObjectUtil.equal(RefundStatusEnum.FAIL.getCode(), executionResultResDTO.getRefundStatus())) {
            //退款失败
            refundStatus = OrderRefundStatusEnum.REFUND_FAIL.getStatus();
        }
        if (ObjectUtil.equal(refundStatus, OrderRefundStatusEnum.REFUNDING.getStatus())) {
            return;
        }
        //非退款中状态，更新订单的退款状态
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<Orders>()
                .eq(Orders::getId, ordersRefund.getId())
                .ne(Orders::getRefundStatus, refundStatus)
                .set(Orders::getRefundStatus, refundStatus)
                .set(ObjectUtil.isNotEmpty(executionResultResDTO.getRefundId()), Orders::getRefundId, executionResultResDTO.getRefundId())
                .set(ObjectUtil.isNotEmpty(executionResultResDTO.getRefundNo()), Orders::getRefundNo, executionResultResDTO.getRefundNo());
        int update = ordersMapper.update(null, updateWrapper);
        //非退款中状态，删除申请退款记录，删除后定时任务不再扫描
        if(update>0){
            //非退款中状态，删除申请退款记录，删除后定时任务不再扫描
            ordersRefundService.removeById(ordersRefund.getId());
        }



    }

    /**
     * 开辟线程退款
     * @param ordersRefundId
     */
    public void requestRefundNewThread(Long ordersRefundId){
        new Thread(()->
        {
            //是否有订单
            OrdersRefund ordersRefund = ordersRefundService.getById(ordersRefundId);
            if(ObjectUtil.isNotNull(ordersRefund)){
                //请求退款
                requestRefundOrder(ordersRefund);
            }

        }).start();

    }

}
